package com.cn.jinl.service;


import afu.org.checkerframework.checker.oigj.qual.O;
import com.cn.jinl.api.IOrderService;
import com.cn.jinl.api.IProductStorageRelateService;
import com.cn.jinl.api.IViolationService;
import com.cn.jinl.conf.Config;
import com.cn.jinl.dao.*;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private OrderBackInfoMapper orderBackInfoMapper;

    @Autowired
    private OrderOutRelateMapper orderOutRelateMapper;

    @Autowired
    private OrderOutInfoMapper orderOutInfoMapper;

    @Autowired
    private IProductStorageRelateService productStorageRelateService;

    @Autowired
    private ProductStorageOutRelateMapper productStorageOutRelateMapper;
    @Autowired
    private ProductStorageRelateMapper productStorageRelateMapper;
    @Autowired
    private IViolationService violationService;

    @Autowired
    private Config config;

    @Override
    public List<Order> getOrderList(QueryForm queryForm) throws Exception {
        //默认查询近三个月
        if (queryForm.getStartTime() == null || queryForm.getStartTime().isEmpty()) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            // 设置endTime为当前时间
            queryForm.setEndTime(sdf1.format(new Date()));
            // 设置startTime为三个月前
            calendar.add(Calendar.MONTH, -3);
            queryForm.setStartTime(sdf.format(calendar.getTime()));
        }
        int count = orderMapper.selectOrderListCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<Order> orders = orderMapper.selectOrderList(queryForm);
        orders.get(0).setCount(count);
        Map<String, Integer> leftMap = productStorageRelateService.getLeftProductStorage();
        for (Order order : orders) {
            String key = order.getItemTypeId() + "-" + order.getGradeValue();
            if (leftMap.containsKey(key)) {
                order.setStorageCount(leftMap.get(key));
            } else {
                order.setStorageCount(0);
            }
        }
        return orders;
    }

    @Override
    public List<String> getOrderGrades() throws Exception {
        return orderMapper.selectOrderGrades();
    }

    @Override
    public List<Order> getOrderOutRelatesByParam(QueryForm queryForm) throws Exception {
        List<Order> orders = orderMapper.selectOrderOutRelatesByParam(queryForm);
        if (StringUtils.isNotEmpty(queryForm.getId())) {
            return orders;
        }
        List<String> backIds = orderBackInfoMapper.selectOrderBackId();
        if (CollectionUtils.isNotEmpty(backIds)) {
            Iterator<Order> iterator = orders.iterator();
            while (iterator.hasNext()) {
                Order next = iterator.next();
                if (backIds.contains(next.getId())) {
                    iterator.remove();
                }
            }
        }
        return orders;
    }

    @Override
    public String addBatchOrder(List<Order> orders) throws Exception {
        if (CollectionUtils.isEmpty(orders)) {
            return "数据不能为空！";
        }
        String yearMothDay = generateUUID.getYearStr();
        String key = "order" + yearMothDay;
        for (Order order : orders) {
            String thNumber = order.getThNumber();
            String peieceNum = order.getPeieceNum();
            String price = order.getPrice();
            if (!CommonUtil.isNumber(peieceNum) || !CommonUtil.isNumber(thNumber) || !CommonUtil.isNumber(price)) {
                return "参数错误【peieceNum or thNumber or price】";
            }
            double totalNum = Double.parseDouble(thNumber) * Double.parseDouble(peieceNum);
            String totalNumStr = NumberUtil.getPoint(totalNum, 4);

            double totalPrice = totalNum * Double.parseDouble(price);
            String totalPriceStr = NumberUtil.getPoint(totalPrice, 2);
            order.setTotalNum(totalNumStr);
            order.setTotalPrice(totalPriceStr);
            int num = generateUUID.getNumberFlag(key);
            String code = yearMothDay + generateUUID.getThreeNumStr(num);
            order.setOrderNum(code);
            order.setId(CommonUtil.generateRandomNum("order-"));
            //待确认
            order.setOrderStatus("1");
        }
        int count = orderMapper.batchInsertOrders(orders);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateOrder(Order order) throws Exception {
        String id = order.getId();
        if (StringUtils.isEmpty(id)) {
            return "主键不能为空";
        }
        Order exist = orderMapper.selectOrderById(id);
        if (null == exist) {
            return "订单不存在";
        }
        if (!StringUtils.equals("1", exist.getOrderStatus())) {
            return "订单不在待确认状态，无法编辑";
        }

        String thNumber = order.getThNumber();
        String peieceNum = order.getPeieceNum();
        String price = order.getPrice();
        if (!CommonUtil.isNumber(peieceNum) || !CommonUtil.isNumber(thNumber) || !CommonUtil.isNumber(price)) {
            return "参数错误【peieceNum or thNumber or price】";
        }
        double totalNum = Double.parseDouble(thNumber) * Double.parseDouble(peieceNum);
        String totalNumStr = NumberUtil.getPoint(totalNum, 4);

        double totalPrice = totalNum * Double.parseDouble(price);
        String totalPriceStr = NumberUtil.getPoint(totalPrice, 2);
        order.setTotalNum(totalNumStr);
        order.setTotalPrice(totalPriceStr);

        OrderExample example = new OrderExample();
        example.createCriteria().andIdEqualTo(id);
        int count = orderMapper.updateByExampleSelective(order, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateOrderProductStatusByIds(List<String> orderIds) throws Exception {
        if (CollectionUtils.isEmpty(orderIds)) {
            return "缺少ids";
        }
        OrderExample example = new OrderExample();
        example.createCriteria().andIdIn(orderIds);
        Order update = new Order();
        update.setOrderStatus("5");
        int count = orderMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateSureOrder(Order order) throws Exception {
        String id = order.getId();
        if (StringUtils.isEmpty(id)) {
            return "主键不能为空";
        }
        Order exist = orderMapper.selectOrderById(id);
        if (null == exist) {
            return "订单不存在";
        }
        if (!StringUtils.equals("1", exist.getOrderStatus())) {
            return "订单不在待确认状态，无法编辑";
        }
        if (StringUtils.isEmpty(order.getGradeValue())) {
            return "规格不能为空";
        }
        if (StringUtils.isEmpty(order.getProductName())) {
            return "产品名称不能为空";
        }
        if (StringUtils.isEmpty(order.getThNumber())) {
            return "单件万只不能为空";
        }
        double totalNum = Double.parseDouble(order.getThNumber()) * Double.parseDouble(exist.getPeieceNum());
        String totalNumStr = NumberUtil.getPoint(totalNum, 4);

        double totalPrice = totalNum * Double.parseDouble(exist.getPrice());
        String totalPriceStr = NumberUtil.getPoint(totalPrice, 2);
        order.setTotalNum(totalNumStr);
        order.setTotalPrice(totalPriceStr);
        order.setOrderStatus("2");
        OrderExample example = new OrderExample();
        example.createCriteria().andIdEqualTo(id);
        int count = orderMapper.updateByExampleSelective(order, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateCompleteOrder(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            return "主键不能为空";
        }
        Order exist = orderMapper.selectOrderById(id);
        if (null == exist) {
            return "订单不存在";
        }
        if (!StringUtils.equals("1", exist.getGoodsStatus())) {
            return "订单发货未完成！";
        }
        Order update = new Order();
        update.setOrderStatus("8");
        OrderExample example = new OrderExample();
        example.createCriteria().andIdEqualTo(id);
        int count = orderMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateSendNeedOrder(List<Order> orders) throws Exception {
        if (CollectionUtils.isEmpty(orders)) {
            return "参数错误！";
        }
        List<String> ids = Lists.newArrayList();
        List<Order> updates = Lists.newArrayList();
        for (Order order : orders) {
            ids.add(order.getId());
            Order update = new Order();
            update.setId(order.getId());
            update.setOrderStatus("3");
            update.setProductPlan("1");
            update.setSendNeedsTime(order.getSendNeedsTime());
            update.setSendNeedsUser(order.getSendNeedsUser());
            updates.add(update);
        }
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andIdIn(ids);
        List<Order> exists = orderMapper.selectByExample(example);
        if (exists.size() != ids.size()) {
            return "订单存在异常！";
        }
        for (Order order : exists) {

            if (!StringUtils.equals(order.getOrderStatus(), "2")) {
                return "订单状态异常，无法下发生产需求！";
            }
            if (Integer.parseInt(order.getPeieceNum()) <= Integer.parseInt(order.getSendGoodsCount())) {
                return "订单已发库存已经满足，无需下发生产需求！";
            }
        }

        int count = orderMapper.batchUpdateOrderNeeds(updates);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateOrderPC(List<String> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return "参数异常！";
        }
        Order update = new Order();
        update.setOrderStatus("4");
        OrderExample example = new OrderExample();
        example.createCriteria().andIdIn(ids);
        int count = orderMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateOrderProduceComplete(String planId) throws Exception {
        List<String> orderIds = orderMapper.selectOrderIdsByPlanId(planId);
        if (CollectionUtils.isEmpty(orderIds)) {
            return "未查询到订单";
        }
        Order update = new Order();
        update.setOrderStatus("6");
        OrderExample example = new OrderExample();
        example.createCriteria().andIdIn(orderIds);
        int count = orderMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String deleteOrders(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            return "主键不能为空";
        }
        Order exist = orderMapper.selectOrderById(id);
        if (null == exist) {
            return "订单不存在";
        }
        if (!StringUtils.equals("1", exist.getOrderStatus())) {
            return "订单不在待确认状态，无法删除";
        }
        OrderExample example = new OrderExample();
        example.createCriteria().andIdEqualTo(id);
        Order update = new Order();
        update.setStatus(Constants.DEL_STATUS);
        int count = orderMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public Map<String, Integer> getOrderNum() throws Exception {
        List<String> statusList = Lists.newArrayList("1", "2", "3", "4", "5", "6", "7");
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andOrderStatusIn(statusList);
        List<Order> orders = orderMapper.selectByExample(example);
        Map<String, Integer> orderMap = Maps.newHashMap();
        orderMap.put("sure", 0);
        orderMap.put("running", 0);
        for (Order order : orders) {
            if (StringUtils.equals(order.getOrderStatus(), "1")) {
                int count = orderMap.get("sure") + 1;
                orderMap.put("sure", count);
            } else if (StringUtils.equals(order.getGoodsStatus(), "0")) {
                int count = orderMap.get("running") + 1;
                orderMap.put("running", count);
            }
        }
        return orderMap;
    }

    @Override
    public Map<String, Integer> getOrderPlanNum() throws Exception {
        List<String> statusList = Lists.newArrayList("1", "3");
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andOrderStatusIn(statusList);
        List<Order> orders = orderMapper.selectByExample(example);
        Map<String, Integer> orderMap = Maps.newHashMap();
        orderMap.put("sure", 0);
        orderMap.put("paichang", 0);
        for (Order order : orders) {
            if (StringUtils.equals(order.getOrderStatus(), "1")) {
                int count = orderMap.get("sure") + 1;
                orderMap.put("sure", count);
            } else {
                int count = orderMap.get("paichang") + 1;
                orderMap.put("paichang", count);
            }
        }
        return orderMap;
    }

    @Override
    public Map<String, Integer> getFirstOrderPlanNum() throws Exception {
        List<String> statusList = Lists.newArrayList("1", "2", "3", "4", "5", "6", "7");
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andOrderStatusIn(statusList);
        List<Order> orders = orderMapper.selectByExample(example);
        Map<String, Integer> orderMap = Maps.newHashMap();
        orderMap.put("sure", 0);
        orderMap.put("paichang", 0);
        orderMap.put("running", 0);
        for (Order order : orders) {
            if (StringUtils.equals(order.getOrderStatus(), "1")) {
                int count = orderMap.get("sure") + 1;
                orderMap.put("sure", count);
            } else if (StringUtils.equals(order.getGoodsStatus(), "0")) {
                int count = orderMap.get("running") + 1;
                orderMap.put("running", count);
            }
            if (StringUtils.equals(order.getOrderStatus(), "3")) {
                int count = orderMap.get("paichang") + 1;
                orderMap.put("paichang", count);
            }
        }

        int violation = violationService.getViolationApproveCount();
        orderMap.put("violation", violation);
        return orderMap;
    }

    @Override
    public Map<String, String> getOrderIdMap() throws Exception {
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS);
        List<Order> orders = orderMapper.selectByExample(example);
        Map<String, String> orderMap = Maps.newHashMap();
        for (Order order : orders) {
            orderMap.put(order.getOrderNum(), order.getId());
        }
        return orderMap;
    }

    @Override
    public Map<String, List<Integer>> getOrderTypeCount() throws Exception {
        OrderExample example = new OrderExample();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String day = simpleDateFormat.format(new Date());
        String currentMoth = day.split("-")[1];
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        Date todayYear = simpleDateFormat.parse(year + "-01-01 00:00:00");
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andCreateTimeGreaterThan(todayYear);
        List<Order> orders = orderMapper.selectByExample(example);
        Map<String, List<Integer>> resultMap = Maps.newHashMap();
        resultMap.put("day", Lists.newArrayList(0, 0, 0, 0));
        resultMap.put("moth", Lists.newArrayList(0, 0, 0, 0));
        resultMap.put("year", Lists.newArrayList(0, 0, 0, 0));
        for (Order order : orders) {
            String createTime = simpleDateFormat.format(order.getCreateTime());
            String moth = createTime.split("-")[1];
            String itemType = order.getItemTypeId();
            int index = 0;
            if (StringUtils.equals("U型", itemType)) {
                index = 0;
            } else if (StringUtils.equals("单支连排", itemType)) {
                index = 1;
            } else if (StringUtils.equals("多支", itemType)) {
                index = 2;
            } else if (StringUtils.equals("伸缩", itemType)) {
                index = 3;
            }
            if (StringUtils.equals(createTime, day)) {
                int count = resultMap.get("day").get(index) + 1;
                resultMap.get("day").set(index, count);
            } else if (StringUtils.equals(currentMoth, moth)) {
                int count = resultMap.get("moth").get(index) + 1;
                resultMap.get("moth").set(index, count);
            }
            int count = resultMap.get("year").get(index) + 1;
            resultMap.get("year").set(index, count);
        }
        return resultMap;
    }

    @Override
    public String updateOrderCompletePlanStatus(String planId) throws Exception {
        List<String> orderIds = orderMapper.selectOrderIdsAndProductByPlanId(planId);
        if (CollectionUtils.isEmpty(orderIds)) {
            return "";
        }
        OrderExample example = new OrderExample();
        example.createCriteria().andIdIn(orderIds);
        Order update = new Order();
        update.setOrderStatus("6");
        int count = orderMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public Map<String, Integer> getYearFirstPageOrderInfo() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String year = simpleDateFormat.format(new Date());
        String todayYear = year + "-01-01 00:00:00";
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date yearTime = simpleDateFormat.parse(todayYear);
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andCreateTimeGreaterThanOrEqualTo(yearTime);
        List<Order> orders = orderMapper.selectByExample(example);

        OrderOutInfoExample outExample = new OrderOutInfoExample();
        outExample.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andCreateTimeGreaterThanOrEqualTo(yearTime).andOrderOutStatusNotEqualTo("2");
        List<OrderOutInfo> orderOutInfos = orderOutInfoMapper.selectByExample(outExample);
        List<String> outOrderIds = Lists.newArrayList();
        for (OrderOutInfo outInfo : orderOutInfos) {
            outOrderIds.add(outInfo.getId());
        }
        List<String> sendOrderIds = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(outOrderIds)) {
            OrderOutRelateExample relateExample = new OrderOutRelateExample();
            relateExample.createCriteria().andOrderOutIdIn(outOrderIds);
            List<OrderOutRelate> relates = orderOutRelateMapper.selectByExample(relateExample);
            for (OrderOutRelate relate : relates) {
                if (!sendOrderIds.contains(relate.getOrderId())) {
                    sendOrderIds.add(relate.getOrderId());
                }
            }
        }

        Map<String, Integer> resultMap = Maps.newHashMap();
        resultMap.put("total", orders.size());
        resultMap.put("complete", 0);
        resultMap.put("handle", 0);
        resultMap.put("unsure", 0);
        resultMap.put("diss", 0);
        QueryForm queryForm = new QueryForm();
        queryForm.setGoodsStatus("0");
        String statusString = "2,3,4,5,6,7";
        String[] statusArray = statusString.split(",");
        List<String> statusList = Arrays.asList(statusArray);
        queryForm.setStatusList(statusList);
        int counts = orderMapper.selectOrderListCount(queryForm);
        resultMap.put("send", counts);
        for (Order order : orders) {
            String orderStatus = order.getOrderStatus();
            if (StringUtils.equals("8", orderStatus)) {
                int count = resultMap.get("complete") + 1;
                resultMap.put("complete", count);
            } else if (StringUtils.equals("9", orderStatus)) {
                int count = resultMap.get("diss") + 1;
                resultMap.put("diss", count);
            } else if (StringUtils.equals("1", orderStatus)) {
//                if (!sendOrderIds.contains(order.getId())) {
                    int count = resultMap.get("unsure") + 1;
                    resultMap.put("unsure", count);
//                }
            } else {
                if (!sendOrderIds.contains(order.getId())) {
                    int count = resultMap.get("handle") + 1;
                    resultMap.put("handle", count);
                }
            }
        }

        int completionRate = 0;
        if (orders.size() > 0) {
            double rate = (double) resultMap.get("complete") / (double) orders.size() * 100;
            completionRate = (int) Math.round(rate);
        }
        resultMap.put("completionRate", completionRate);
        return resultMap;
    }

    @Override
    public Map<String, Object> getFirstPageOrderInfo() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String year = simpleDateFormat.format(new Date());
        String todayYear = year + "-01-01 00:00:00";
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date yearTime = simpleDateFormat.parse(todayYear);
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andCreateTimeGreaterThanOrEqualTo(yearTime);
        List<Order> orders = orderMapper.selectByExample(example);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String currentTime = simpleDateFormat1.format(new Date());
        String currentMoth = currentTime.split("-")[1];
        int totalCount = orders.size();
        int completeCount = 0;
        int doingCount = 0;
        int mothCount = 0;
        int dayCount = 0;
        int unSureCount = 0;
        for (Order order : orders) {
            String createTime = simpleDateFormat1.format(order.getCreateTime());
            String orderStatus = order.getOrderStatus();
            if (StringUtils.equals(orderStatus, "1")) {
                ++unSureCount;
            } else if (StringUtils.equals(orderStatus, "8")) {
                ++completeCount;
            } else if (!StringUtils.equals(orderStatus, "1") && !StringUtils.equals(orderStatus, "8") && !StringUtils.equals(orderStatus, "9")) {
                ++doingCount;
            }
            if(StringUtils.equals(createTime,currentTime)){
                ++dayCount;
            }
            if(StringUtils.equals(createTime.split("-")[1],currentMoth)){
                ++mothCount;
            }
        }
        Map<String,Object> results = Maps.newLinkedHashMap();
        results.put("totalCount",totalCount);
        results.put("completeCount",completeCount);
        results.put("doingCount",doingCount);
        results.put("mothCount",mothCount);
        results.put("dayCount",dayCount);
        results.put("unSureCount",unSureCount);
        return results;
    }

    @Override
    public List<Order> getFirstPageOrderInfoList() throws Exception {
        List<String> orderStatusList = Lists.newArrayList("1","2","3","4","5","6","7");
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andOrderStatusIn(orderStatusList);
        example.setOrderByClause("order_num asc");
        List<Order> orders = orderMapper.selectByExample(example);
        return orders;
    }

    @Override
    public List<Order> getNameByQuery(String queryString) {
        return orderMapper.getNameByQuery(queryString);
    }

    @Override
    public String cancelOrder(QueryForm queryForm) throws Exception {
        List<String> ids = queryForm.getIds();
        if (CollectionsUtil.isEmpty(ids)){
            return "请选中要作废的数据！";
        }
        //TODO 设备表可能关联其他表，判断是否可以删除

        Order order = new Order();
        order.setStatus(Constants.DEL_STATUS);
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andIdIn(ids);
        int count = orderMapper.updateByExampleSelective(order,orderExample);

        return CommonUtil.outStr(count);
    }

    @Override
    public List<Order> getInventory(QueryForm queryForm) throws Exception {
//        int count = orderMapper.selectOrderListIsHavingCount(queryForm);
//        if (count == 0) {
//            return Lists.newArrayList();
//        }
        List<Order> orders = orderMapper.selectOrderListByisHaving(queryForm);
//        if (orders.size()==0){
//            return orders;
//        }else {
//            orders.get(0).setCount(count);
//        }
        Map<String, Integer> leftMap = productStorageRelateService.getLeftProductStorage();
        for (Order order : orders) {
            String key = order.getItemTypeId() + "-" + order.getGradeValue();
            if (leftMap.containsKey(key)) {
                order.setStorageCount(leftMap.get(key));
            } else {
                order.setStorageCount(0);
            }
        }
        return orders;
    }
    @Override
    public Map<String, Object> getAllTypesNumList(QueryForm queryForm) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.getAllTypesNumList(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));

        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        return result;
    }

    @Override
    public Map<String, Object> customerOrder(QueryForm queryForm) throws Exception {

        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.customerOrder(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));

        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        return result;
    }

    @Override
    public void exportAllTypesNumList(QueryForm queryForm, HttpServletResponse response) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.getAllTypesNumList(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));


        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        result.put("name", queryForm.getName());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         result.put("startTime", simpleDateFormat.format(date));

        String fileName = CommonUtil.generateRandomNum("allTypesNum-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"全类吸管产品产量动态数据.xlsx",result,"allTypesNum_check.xlsx", response);
    }

    @Override
    public void exportAllTypesPriceList(QueryForm queryForm, HttpServletResponse response) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.getAllTypesCount(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));

        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);

        result.put("name", queryForm.getName());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result.put("startTime", simpleDateFormat.format(date));

        String fileName = CommonUtil.generateRandomNum("allTypesOrder-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"全类吸管产品销售额动态数据.xlsx",result,"allTypesOrder_check.xlsx", response);
    }

    @Override
    public void exportCustomerDelivery(QueryForm queryForm, HttpServletResponse response) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.customerDelivery(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));
        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        result.put("name", queryForm.getName());
        result.put("customer", queryForm.getCustomer());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result.put("startTime", simpleDateFormat.format(date));

        String fileName = CommonUtil.generateRandomNum("customerDelivery-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"单客户年度交货数据.xlsx",result,"customerDelivery_check.xlsx", response);
    }

    @Override
    public void exportCustomerOrder(QueryForm queryForm, HttpServletResponse response) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.customerOrder(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));

        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        result.put("name", queryForm.getName());
        result.put("customer", queryForm.getCustomer());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result.put("startTime", simpleDateFormat.format(date));

        String fileName = CommonUtil.generateRandomNum("customerOrder-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"单客户年度销售额数据.xlsx",result,"customerOrder_check.xlsx", response);
    }

    @Override
    public void exportOrderAndSalesRanking(QueryForm queryForm, HttpServletResponse response) throws Exception {
        //列表数据
        List<OrderRankingVo> orders  =orderMapper.OrderAndSalesRanking(queryForm);
        Map<String, Object> result = new HashMap<>();
        result.put("tableData", orders);
        result.put("name", queryForm.getName());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result.put("startTime", simpleDateFormat.format(date));

        String fileName = CommonUtil.generateRandomNum("orderAndSalesRanking-")+".xlsx";
        String filePath = config.filePath+fileName;
        TemplateExcelUtils.downLoadExcel(filePath,"订单及销售额排名.xlsx",result,"orderAndSalesRanking_check.xlsx", response);
    }

    @Override
//    public List<InventoryVo> getCurrentInventory(QueryForm queryForm) throws Exception {
//        // 获取所有的规格、出库数量和箱码
//        List<ProductStorageOutRelate> productStorageOutRelates = productStorageOutRelateMapper.selectGradeValue(queryForm);
//        if (CollectionUtils.isEmpty(productStorageOutRelates)) {
//            return new ArrayList<>();
//        }
//
//        // 收集所有箱码和规格
//        List<String> allBoxCodes = new ArrayList<>();
//        List<String> allGradeValues = productStorageOutRelates.stream()
//                .map(ProductStorageOutRelate::getGradeValue)
//                .distinct()
//                .collect(Collectors.toList());
//
//        for (ProductStorageOutRelate relate : productStorageOutRelates) {
//            if (StringUtils.isNotBlank(relate.getBoxCodes())) {
//                List<String> boxCodeList = Arrays.asList(relate.getBoxCodes().split(","));
//                allBoxCodes.addAll(boxCodeList);
//            }
//        }
//
//        // 去重箱码
//        allBoxCodes = allBoxCodes.stream().distinct().collect(Collectors.toList());
//
//        // 批量查询报工数量（根据品类、规格和箱码查询）
//        Map<String, Integer> reportingCountByBoxCodeMap = getCountByBoxCodesWithCondition(
//                queryForm.getItemId(), allGradeValues, allBoxCodes);
//
//        List<InventoryVo> resultList = new ArrayList<>();
//        for (ProductStorageOutRelate productStorageOutRelate : productStorageOutRelates) {
//            InventoryVo inventoryVo = new InventoryVo();
//            inventoryVo.setGradeValue(productStorageOutRelate.getGradeValue());
//
//            // 计算该规格对应的所有箱码的报工数量总和
//            int countByReporting = 0;
//            if (StringUtils.isNotBlank(productStorageOutRelate.getBoxCodes())) {
//                List<String> boxCodesForThisGrade = Arrays.asList(productStorageOutRelate.getBoxCodes().split(","));
//                for (String boxCode : boxCodesForThisGrade) {
//                    countByReporting += reportingCountByBoxCodeMap.getOrDefault(boxCode, 0);
//                }
//            }
//
//            inventoryVo.setReportedQuantity(String.valueOf(countByReporting));
//
//            // 设置库存数量
//            int stockCount = productStorageOutRelate.getOutTotalCount();
//            inventoryVo.setQuantityInStock(String.valueOf(stockCount));
//
//            // 当前库存 = 报工数量 - 库存数量
//            int currentInventory = countByReporting - stockCount;
//            inventoryVo.setCurrentInventory(String.valueOf(currentInventory));
//
//            inventoryVo.setGradeValueNum(String.valueOf(productStorageOutRelates.size()));
//            resultList.add(inventoryVo);
//        }
//
//
//        return resultList;
//    }


    public List<InventoryVo> getCurrentInventory(QueryForm queryForm) throws Exception {

        // 获取所有的规格跟出库数量
        List<ProductStorageOutRelate> productStorageOutRelates = productStorageOutRelateMapper.selectGradeValue(queryForm);
        if (CollectionUtils.isEmpty(productStorageOutRelates)) {
            return new ArrayList<>();
        }

        // 查询的gradeValue
        List<String> gradeValues = productStorageOutRelates.stream()
                .map(ProductStorageOutRelate::getGradeValue)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询报工数量（一次性查询所有规格）
        Map<String, Integer> reportingCountMap = productStorageRelateService.getCountByReportingBatch(queryForm.getItemId(), gradeValues);

        List<InventoryVo> resultList = new ArrayList<>();
        for (ProductStorageOutRelate productStorageOutRelate : productStorageOutRelates) {
            InventoryVo inventoryVo = new InventoryVo();
            // 设置规格值
            inventoryVo.setGradeValue(productStorageOutRelate.getGradeValue());

            // 从批量查询结果中获取报工数量
            int countByReporting = reportingCountMap.getOrDefault(productStorageOutRelate.getGradeValue(), 0);
            inventoryVo.setReportedQuantity(String.valueOf(countByReporting));

            // 设置库存数量
            int stockCount = productStorageOutRelate.getOutTotalCount();
            inventoryVo.setQuantityInStock(String.valueOf(stockCount));

            // 当前库存 = 报工数量 - 库存数量
            int currentInventory = countByReporting - stockCount;
            inventoryVo.setCurrentInventory(String.valueOf(currentInventory));

            inventoryVo.setGradeValueNum(String.valueOf(productStorageOutRelates.size()));
            resultList.add(inventoryVo);
        }


        return resultList;
    }
//    public List<InventoryVo> getCurrentInventory(QueryForm queryForm) throws Exception {
//        // 1. 先查询入库数据（报工数据）
//        List<ProductStorageRelate> inDataList = productStorageRelateMapper.selectInDataWithBoxCodes(queryForm);
//        if (CollectionUtils.isEmpty(inDataList)) {
//            return new ArrayList<>();
//        }
//
//        // 2. 收集所有规格和对应的箱码
//        Map<String, List<String>> gradeValueToBoxCodes = new HashMap<>();
//        for (ProductStorageRelate inData : inDataList) {
//            if (StringUtils.isNotBlank(inData.getBoxCodes())) {
//                List<String> boxCodeList = Arrays.asList(inData.getBoxCodes().split(","));
//                gradeValueToBoxCodes.put(inData.getGradeValue(), boxCodeList);
//            }
//        }
//        // 3. 根据每个规格和对应的箱码查询出库数据
//        Map<String, Integer> outCountByGradeValue = new HashMap<>();
//        for (Map.Entry<String, List<String>> entry : gradeValueToBoxCodes.entrySet()) {
//            String gradeValue = entry.getKey();
//            List<String> boxCodes = entry.getValue();
//
//            // 查询该规格下对应箱码的出库数据
//            List<ProductStorageOutRelate> outDataForGrade = productStorageOutRelateMapper.selectOutDataByGradeAndBoxCodes(
//                    queryForm.getItemId(), gradeValue, boxCodes);
//
//            // 汇总该规格的出库数量
//            int totalOutCount = outDataForGrade.stream()
//                    .mapToInt(ProductStorageOutRelate::getOutTotalCount)
//                    .sum();
//
//            outCountByGradeValue.put(gradeValue, totalOutCount);
//        }
//
//
//        List<InventoryVo> resultList = new ArrayList<>();
//        for (ProductStorageRelate inData : inDataList) {
//            InventoryVo inventoryVo = new InventoryVo();
//            inventoryVo.setGradeValue(inData.getGradeValue());
//
//            // 设置报工数量（入库数量）
//            int reportedQuantity = inData.getInTotalCount();
//            inventoryVo.setReportedQuantity(String.valueOf(reportedQuantity));
//
//            // 设置库存数量（出库数量）
//            int stockCount = outCountByGradeValue.getOrDefault(inData.getGradeValue(), 0);
//            inventoryVo.setQuantityInStock(String.valueOf(stockCount));
//
//            // 当前库存 = 报工数量（入库） - 库存数量（出库）
//            int currentInventory = reportedQuantity - stockCount;
//            inventoryVo.setCurrentInventory(String.valueOf(currentInventory));
//
//            inventoryVo.setGradeValueNum(String.valueOf(inDataList.size()));
//            resultList.add(inventoryVo);
//        }
//
//        return resultList;
//    }


    private Map<String, Integer> getCountByBoxCodesWithCondition(String itemId, List<String> gradeValues, List<String> boxCodes) {
        if (CollectionUtils.isEmpty(boxCodes)) {
            return new HashMap<>();
        }

        List<Map<String, Object>> results = productStorageRelateMapper.selectReportingCountByBoxCodesWithCondition(
                itemId, gradeValues, boxCodes);

        // key为box_code，value为数量
        return results.stream()
                .collect(Collectors.toMap(
                        result -> (String) result.get("box_code"),
                        result -> ((Number) result.get("count")).intValue()
                ));
    }

    @Override
    public void exportInventoryInfo(QueryForm queryForm, HttpServletResponse response) throws Exception {
        // 获取所有的规格跟出库数量
        List<ProductStorageOutRelate> productStorageOutRelates = productStorageOutRelateMapper.selectGradeValue(queryForm);


        // 查询的gradeValue
        List<String> gradeValues = productStorageOutRelates.stream()
                .map(ProductStorageOutRelate::getGradeValue)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询报工数量（一次性查询所有规格）
        Map<String, Integer> reportingCountMap = productStorageRelateService.getCountByReportingBatch(queryForm.getItemId(), gradeValues);

        List<InventoryVo> resultList = new ArrayList<>();
        for (ProductStorageOutRelate productStorageOutRelate : productStorageOutRelates) {
            InventoryVo inventoryVo = new InventoryVo();
            // 设置规格值
            inventoryVo.setGradeValue(productStorageOutRelate.getGradeValue());

            // 从批量查询结果中获取报工数量
            int countByReporting = reportingCountMap.getOrDefault(productStorageOutRelate.getGradeValue(), 0);
            inventoryVo.setReportedQuantity(String.valueOf(countByReporting));

            // 设置库存数量
            int stockCount = productStorageOutRelate.getOutTotalCount();
            inventoryVo.setQuantityInStock(String.valueOf(stockCount));

            // 当前库存 = 报工数量 - 库存数量
            int currentInventory = countByReporting - stockCount;
            inventoryVo.setCurrentInventory(String.valueOf(currentInventory));

            inventoryVo.setGradeValueNum(String.valueOf(productStorageOutRelates.size()));
            resultList.add(inventoryVo);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("tableData", resultList);
        result.put("name", queryForm.getName());
        result.put("itemId", queryForm.getItemId());
        result.put("num", resultList.get(0).getGradeValueNum());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        result.put("startTime", simpleDateFormat.format(date));

        String fileName = CommonUtil.generateRandomNum("inventoryInfo-")+".xlsx";
        String filePath = config.filePath+fileName;
        String outFileName=simpleDateFormat1.format(date)+"_库存_"+queryForm.getItemId()+".xlsx";

        TemplateExcelUtils.downLoadExcel(filePath,outFileName,result,"inventoryInfo_check.xlsx", response);

    }

    @Override
    public List<ProductStorageOutRelate> getOrderGradesByApp(QueryForm queryForm) throws Exception {
        List<ProductStorageOutRelate> productStorageOutRelates = productStorageOutRelateMapper.selectGradeValue(queryForm);
        return productStorageOutRelates;
    }

    @Override
        public String balancedInventory() throws Exception {
            try {
                // 获取所有品类规格组合
                List<Map<String, Object>> itemGrades = productStorageRelateMapper.selectAllItemGradeCombinations();

                // 遍历每个品类规格并处理
                for (Map<String, Object> itemGrade : itemGrades) {
                    String itemTypeId = (String) itemGrade.get("itemTypeId");
                    String gradeValue = (String) itemGrade.get("gradeValue");

                    if (itemTypeId != null && gradeValue != null) {
                        processItemGrade(itemTypeId, gradeValue);
                    }
                }

                return "库存平衡完成";

            } catch (Exception e) {
                throw new Exception("平衡库存失败 ");
            }
        }

    @Override
    public List<Order> getOrderCount(QueryForm queryForm) throws Exception {

        int count = orderMapper.getOrderCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<Order> orders = orderMapper.selectOrderList(queryForm);
        orders.get(0).setCount(count);
        return orders;
    }


    private void processItemGrade(String itemTypeId, String gradeValue) {
        // 查询入库表中该品类规格的所有箱码
        List<String> inBoxCodes = productStorageRelateMapper.selectBoxCodesByItemAndGrade(itemTypeId, gradeValue);
        if (inBoxCodes == null || inBoxCodes.isEmpty()) {
            return;
        }

        // 查询出库表中已存在的箱码
        List<String> existingBoxCodes = productStorageOutRelateMapper.selectExistingBoxCodes(inBoxCodes);

        //找出缺失的箱码
        List<String> missingBoxCodes = new ArrayList<>();
        for (String boxCode : inBoxCodes) {
            if (!existingBoxCodes.contains(boxCode)) {
                missingBoxCodes.add(boxCode);
            }
        }

        if (missingBoxCodes.isEmpty()) {
            return;
        }

        //获取缺失箱码的完整信息
        List<Map<String, Object>> missingRecords = productStorageRelateMapper.selectByBoxCodesAndItemGrade(missingBoxCodes, itemTypeId, gradeValue);

        if (missingRecords == null || missingRecords.isEmpty()) {
            return;
        }

        //批量插入到出库表
        List<Map<String, Object>> insertList = new ArrayList<>();
        for (Map<String, Object> record : missingRecords) {
            Map<String, Object> outRecord = new HashMap<>();
            outRecord.put("stroageOutId", "1");
            outRecord.put("boxCode", record.get("box_code"));
            outRecord.put("relateId", "1");
            outRecord.put("outCount", "1");
            outRecord.put("itemTypeId", itemTypeId);
            outRecord.put("gradeValue", gradeValue);
            insertList.add(outRecord);
        }

        if (!insertList.isEmpty()) {
            productStorageOutRelateMapper.batchInsert(insertList);
        }
    }



    @Override
    public Map<String, Object> getAllTypesPriceList(QueryForm queryForm) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.getAllTypesCount(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));

        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        return result;

    }

    @Override
    public Map<String, Object> OrderAndSalesRanking(QueryForm queryForm) throws Exception {
        //列表数据
        List<OrderRankingVo> orders  =orderMapper.OrderAndSalesRanking(queryForm);
        //订单数据
        //取前三条数据
        List<OrderRankingVo> orderTop3=orderMapper.OrderRanking3(queryForm);
        //取后一条数据
        List<OrderRankingVo> orderLast1=orderMapper.OrderRankingLast1(queryForm);
        //金额数据
        //取前三条数据
        List<OrderRankingVo> priceTop3=orderMapper.priceRanking3(queryForm);
        //取后一条数据
        List<OrderRankingVo> priceLast1 =orderMapper.priceRankingLast1(queryForm);
        Map<String, Object> orderMap = new HashMap<>(4);
        orderMap.put("top3", orderTop3);
        orderMap.put("last1", orderLast1);

        Map<String, Object> priceMap = new HashMap<>(4);
        priceMap.put("top3", priceTop3);
        priceMap.put("last1", priceLast1);
        Map<String, Object> result = new HashMap<>();
        result.put("tableData", orders);
        result.put("orderRank", orderMap);
        result.put("priceRank", priceMap);

        return result;
    }

    @Override
    public Map<String, Object> customerDelivery(QueryForm queryForm) throws Exception {
        String year = queryForm.getYear();

        Map<String, String> categoryMap = new LinkedHashMap<String, String>() {{
            put("ss", "伸缩");
            put("dz", "多支");
            put("ux", "U型");
            put("dzlp", "单支连排");
        }};
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("year", year);

        List<Map<String, Object>> monthlyData = new ArrayList<>();
        Map<String, BigDecimal> annualTotals = new LinkedHashMap<>();

        // 初始化年度总计为 BigDecimal.ZERO
        for (String enCategory : categoryMap.keySet()) {
            annualTotals.put(enCategory, BigDecimal.ZERO);
        }
        annualTotals.put("total", BigDecimal.ZERO);

        for (int month = 1; month <= 12; month++) {
            String monthStr = String.format("%02d", month);
            String monthName = month + "月";
            String startTime = year + "-" + monthStr;
            queryForm.setStartTime(startTime);

            Map<String, Object> monthData = new LinkedHashMap<>();
            monthData.put("month", monthName);

            BigDecimal monthlyTotal = BigDecimal.ZERO;
            for (Map.Entry<String, String> entry : categoryMap.entrySet()) {
                String enCategory = entry.getKey();
                String zhCategory = entry.getValue();

                queryForm.setProcessCategory(zhCategory);
                BigDecimal count = orderMapper.customerDelivery(queryForm);

                monthData.put(enCategory, count);
                monthlyTotal = monthlyTotal.add(count); // 使用add方法进行加法
                annualTotals.put(enCategory, annualTotals.get(enCategory).add(count));
            }

            monthData.put("monthlyTotal", monthlyTotal);
            monthlyData.add(monthData);
            annualTotals.put("total", annualTotals.get("total").add(monthlyTotal));
        }

        Map<String, Object> annualData = new LinkedHashMap<>();
        for (String enCategory : categoryMap.keySet()) {
            annualData.put(enCategory + "AnnualTotal", annualTotals.get(enCategory));
        }
        annualData.put("annualTotal", annualTotals.get("total"));

        result.put("monthlyData", monthlyData);
        result.put("annualData", annualData);
        return result;

    }



}
